package com.roger.tool.utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

public class DeviceUtils {

	public static String getDeviceId(Context context) {
		String deviceId = "";
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		deviceId = tm.getDeviceId();
		if (deviceId == null) {
			deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
		}
		if (deviceId != null) {
			return deviceId;
		} else {
			return "unknown";
		}

	}

	public static String encodeData(String s) {
		try {
			return URLEncoder.encode(s, "UTF-8");
		} catch (Exception e) {

			return "";
		}
	}

	public static String getImei(Context context) {
		String imei = ((TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE)).getDeviceId();
		if (imei == null || imei.length() != 15) {
			imei = getImsi(context);

			// 记录IMEI的真实性
			SharedUtil.editBoolean(context, "device_authenticity", "Key_IMEI_A", false);
		} else {
			SharedUtil.editBoolean(context, "device_authenticity", "Key_IMEI_A", true);
		}
		return imei;
	}

	/**
	 * 获取手机imsi码
	 * 
	 * @param pContext
	 * @return 如果获取不到，则返回000000
	 */
	public static final String getImsi(Context pContext) {
		String imsi = ((TelephonyManager) pContext.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
		if (imsi == null || imsi.length() != 15) {
			imsi = ImsiUtil.getImsi(pContext);

			// 记录IMSI的真实性
			SharedUtil.editBoolean(pContext, "device_authenticity", "Key_IMSI_A", false);
		} else {
			SharedUtil.editBoolean(pContext, "device_authenticity", "Key_IMSI_A", true);
		}
		return imsi;
	}

	public static boolean getImeiAuthenticity(Context context) {
		return SharedUtil.getBoolean(context, "device_authenticity", "Key_IMEI_A", false);
	}

	public static boolean getImsiAuthenticity(Context context) {
		return SharedUtil.getBoolean(context, "device_authenticity", "Key_IMSI_A", false);
	}

	public static String getAppName(Context pContext) {
		try {
			PackageInfo pkg = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0);
			String appName = pkg.applicationInfo.loadLabel(pContext.getPackageManager()).toString();
			return appName;
		} catch (Exception e) {
		}
		return "error";
	}

	public static final String getIccid(Context context) {
		try {
			return IccidUtil.getIccid(context);
		} catch (Exception e) {
			return "";
		}
	}

	public static int getVersionCode(Context context) {
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			return pinfo.versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static String getMacAddress(Context pContext) {
		String macAddress = "unknown";
		try {
			WifiManager wifi = (WifiManager) pContext.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			macAddress = info.getMacAddress();
			if (macAddress == null || macAddress.equals("")) {
				macAddress = "unknown";
			}
			return macAddress;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return macAddress;
	}

	/**
	 * 如果要用于URL，请先经过编码
	 * 
	 * @return
	 */
	public static String getModel() {
		return Build.MODEL;
	}

	/**
	 * 如果要用于URL，请先经过编码
	 * 
	 * @return
	 */
	public static String getManufacturer() {
		return Build.MANUFACTURER;
	}

	/**
	 * 如果要用于URL，请先经过编码
	 * 
	 * @return
	 */
	public static String getRelease() {
		return Build.VERSION.RELEASE;
	}

	public static String getNetworkTypeName(Context pContext) {
		try {
			ConnectivityManager connectivity = (ConnectivityManager) pContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
			if (networkInfo == null) {
				return "GPRS";
			}
			String typeName = networkInfo.getTypeName();
			if (typeName.compareTo("MOBILE") == 0 || typeName.compareTo("mobile") == 0) {
				return "GPRS";
			}
			return typeName.trim();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "GPRS";
	}

	public static String getNetWorkType(Context pContext) {
		String str = "";
		try {
			ConnectivityManager connectivity = (ConnectivityManager) pContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isConnected()) {
				String typeName = networkInfo.getTypeName();
				if (typeName.equalsIgnoreCase("WIFI")) {
					str = "WIFI";
				} else if (typeName.equalsIgnoreCase("MOBILE")) {
					str = ((TelephonyManager) pContext.getSystemService(Activity.TELEPHONY_SERVICE)).getNetworkType() + "";
				} else {
					str = "";
				}
			}
		} catch (Exception e) {
			str = "";
		}
		return str;
	}

	public static String getNetworkClass(Context pContext) {
		return NetworkClassUtil.getNetworkClass(DeviceUtils.getNetWorkType(pContext));
	}

	public static String getIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return "";
	}

	private static int mGsmCid = -1;
	private static int mGsmLac = -1;

	/**
	 * 0,cid;1,lac
	 * 
	 * @param pContext
	 * @return
	 */
	public static void updataGsmCidLac(Context pContext) {
		try {
			TelephonyManager tm = (TelephonyManager) pContext.getSystemService(Context.TELEPHONY_SERVICE);
			GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
			mGsmCid = location.getCid();
			mGsmLac = location.getLac();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 获取先请先调用updataGsmCidLac
	 * 
	 * @return
	 */
	public static int getGsmCid() {
		return mGsmCid;
	}

	/**
	 * 获取先请先调用updataGsmCidLac
	 * 
	 * @return
	 */
	public static int getGsmLac() {
		return mGsmLac;
	}

	private static double mLatitude = 0.0d;
	private static double mLongitude = 0.0d;

	public static void updateLatitudeLongitude(Context pContext) {
		try {
			LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (location != null) {
				mLatitude = location.getLatitude();
				mLongitude = location.getLongitude();
			}
			if (mLatitude == 0.0d || mLongitude == 0.0d) {
				location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location != null) {
					mLatitude = location.getLatitude(); // 经度
					mLongitude = location.getLongitude(); // 纬度
				}
			}
			// LogSdk.v("updateLatitudeLongitude--->" + mLatitude + "__" +
			// mLongitude);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 经度，获取先请先调用updateLatitudeLongitude
	 * 
	 * @return
	 */
	public static double getLatitude() {
		return mLatitude;
	}

	/**
	 * 纬度，获取先请先调用updateLatitudeLongitude
	 * 
	 * @return
	 */
	public static double getLongitude() {
		return mLongitude;
	}

	public static String getSSID(Context pContext) {
		try {
			return ((WifiManager) pContext.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getSSID();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "";
		}
	}

	public static String getCarrierName(Context pContext) {
		try {
			String carrierName = ((TelephonyManager) pContext.getSystemService(Activity.TELEPHONY_SERVICE))
					.getNetworkOperatorName();
			return carrierName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return DeviceUtils.getImsi(pContext);
	}

	public static int getWidthPixels(Context pContext) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		((WindowManager) pContext.getSystemService(Activity.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics.widthPixels;
	}

	public static int getHeightPixels(Context pContext) {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		((WindowManager) pContext.getSystemService(Activity.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics.heightPixels;
	}

	public static int getScreenDensity(Context pContext) {
		try {
			DisplayMetrics displayMetrics = new DisplayMetrics();
			((WindowManager) pContext.getSystemService(Activity.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
			return displayMetrics.densityDpi;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static String getCpuRatioMax() {
		String result = "";
		ProcessBuilder cmd;
		try {
			String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
			cmd = new ProcessBuilder(args);
			Process process = cmd.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[24];
			while (in.read(re) != -1) {
				result = result + new String(re);
			}
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
			result = "N/A";
		}
		return result.trim();
	}

	@SuppressWarnings("resource")
	public static String getCpuRatioCur() {
		try {
			FileReader fileReader = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
			return new BufferedReader(fileReader).readLine().trim();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	@SuppressWarnings("resource")
	public static String getMenoryRatio() {
		String str1 = "/proc/meminfo";
		String str2 = "";
		try {
			FileReader fr = new FileReader(str1);
			BufferedReader bufferedReader = new BufferedReader(fr, 8192);
			if ((str2 = bufferedReader.readLine()) != null) {
				String menoryRatio = str2.substring(str2.indexOf(":") + 2, str2.indexOf("k") - 1).trim();
				return menoryRatio;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getCountryCode() {
		String str;
		try {
			str = Locale.getDefault().getCountry();
		} catch (Exception localException) {
			str = "";
		}
		return emptyStr(str);
	}

	public static String getLanguageCode() {
		String str;
		try {
			str = Locale.getDefault().getLanguage();
		} catch (Exception localException) {
			str = "";
		}
		return emptyStr(str);
	}

	private static String emptyStr(String pStr) {
		if (TextUtils.isEmpty(pStr))
			return "";
		return pStr;
	}

	public static long[] getTcpRxTxBytes(Context pContext) {
		int uid = getUid(pContext);
		String rcvPath = "proc/uid_stat/" + uid + "/tcp_rcv";
		String sndPath = "proc/uid_stat/" + uid + "/tcp_snd";
		FileReader rcvFileReader = null;
		BufferedReader rcvBufferedReader = null;
		long rcvData = 0;
		try {
			rcvFileReader = new FileReader(rcvPath);
			rcvBufferedReader = new BufferedReader(rcvFileReader, 500);
			rcvData = Long.parseLong(rcvBufferedReader.readLine().toString().trim());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rcvFileReader != null) {
					rcvFileReader.close();
				}
				if (rcvBufferedReader != null) {
					rcvBufferedReader.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		FileReader sndFileReader = null;
		BufferedReader sndBufferedReader = null;
		long sndData = 0;
		try {
			sndFileReader = new FileReader(sndPath);
			sndBufferedReader = new BufferedReader(sndFileReader, 500);
			sndData = Long.parseLong(sndBufferedReader.readLine().toString().trim());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (sndFileReader != null) {
					sndFileReader.close();
				}
				if (sndBufferedReader != null) {
					sndBufferedReader.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return new long[] { rcvData < 0L ? 0L : rcvData, sndData < 0L ? 0L : sndData };
	}

	private static int getUid(Context pContext) {
		try {
			return pContext.getPackageManager().getApplicationInfo(pContext.getPackageName(), 1).uid;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

	/**
	 * 是否飞行模式
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isAirplaneModeOn(Context context) {
		return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
	}

	// sim卡是否可读
	public static boolean isCanUseSim(Context pContext) {
		try {
			TelephonyManager telMgr = (TelephonyManager) pContext.getSystemService(Context.TELEPHONY_SERVICE);
			return TelephonyManager.SIM_STATE_READY == telMgr.getSimState();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
